package com.fau.wm.action.index;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.fau.wm.action.PublicAction;
import com.fau.wm.entity.MedicalAdmin;
import com.fau.wm.entity.MedicalRecall;
import com.fau.wm.entity.MedicalRecallDetail;
import com.fau.wm.util.FileNameEncoderUtil;
import com.fau.wm.util.SystemConfig;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @desc 入库基本信息Action
 * @author kangyj
 * @datetime 2014年8月12日,上午10:25:47
 */
@Controller
@Scope("prototype")
@ParentPackage("default")
@Namespace("/")
public class RecallAction extends PublicAction implements ModelDriven<MedicalRecall> {

	private static final long serialVersionUID = -7831601773482746067L;
	
	private MedicalRecall recall = new MedicalRecall();

	/**
	 * @desc 出库初始化列表页
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月12日,上午10:27:20
	 */
	@Action(value = "recall_init", results = {@Result(name = SUCCESS, location = "recall_init.jsp")})
	public String init(){
		return SUCCESS;
	}
	
	/**
	 * @desc 查询出库列表
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月12日,上午10:29:18
	 */
	@Action(value = "recall_view")
	public String view(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = ServletActionContext.getContext().getParameters();
		MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		recall.setHospitalId(user.getEnterpriseId());
		pageBean = this.baseAllService.getRecallManagerService().findRecallByPage(recall, map);
		map.clear();
		map.put("total", pageBean.getTotalRow());
		map.put("data", pageBean.getResult());
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 添加出库单基本信息
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月12日,下午2:20:45
	 */
	@Action(value = "recall_add", results = {@Result(name = SUCCESS, location = "recall_add.jsp")})
	public String add(){
		return SUCCESS;
	}
	
	/**
	 * @desc 保存入库单基本信息
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月12日,下午2:23:09
	 */
	@Action(value = "recall_save")
	public String save(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin writeUser = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Boolean flag = this.baseAllService.getRecallManagerService().saveRecall(recall, writeUser);
		if(flag){
			map.put("success", true);
		}else{
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 验证输入编码是否已存在 
	 * @return
	 * @author suny
	 * @datetime 2014年9月4日,下午3:13:48
	 */
	@Action(value = "recall_ver_serialnum")
	public String verSerialNum(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(StringUtils.isNotBlank(recall.getSerialNum())){
			Boolean flag = this.baseAllService.getRecallManagerService().verSerialNum(recall.getSerialNum(), admin.getEnterpriseId());
			if(flag){
				map.put("result", true);
			}else{
				map.put("result", false);
			}
		}else{
			map.put("message", "error");
			}
		formatJSON(response, map);
		return null;
	}

	/**
	 * @desc 查询仓库集合
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月1日,下午8:09:13
	 */
	@Action(value = "recall_find_warehouse")
	public String findWarehouseList() {
		HttpServletResponse response = ServletActionContext.getResponse();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		list = this.baseAllService.getBaseDataService().findWarehouseByHospital(admin.getEnterpriseId());
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 编辑出库基本信息
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月12日,下午3:16:54
	 */
	@Action(value = "recall_edit", results = {@Result(name = SUCCESS, location = "recall_edit.jsp")})
	public String edit(){
		return SUCCESS;
	}
	
	/**
	 * @desc 保存编辑出库基本信息
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月12日,下午3:22:49
	 */
	@Action(value = "recall_save_edit")
	public String saveEdit(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(recall.getId())){
			this.baseAllService.getRecallManagerService().saveEditRecall(recall);
			map.put("success", true);
		}else{
			map.put("message", "error");
			}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 删除出库单
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月12日,下午3:28:13
	 */
	@Action(value = "recall_del")
	public String del(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(recall.getId())){
			this.baseAllService.getRecallManagerService().delRecall(recall);
			map.put("success", true);
			formatJSON(response, map);
		}
		return null;
	}
	
	/**
	 * @desc 确定完成出库
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月13日,下午9:29:05
	 */
	@Action(value = "recall_recall")
	public String recall(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin auditUser = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(StringUtils.isNotBlank(recall.getId())){
			List<MedicalRecallDetail> recallDetailList = this.baseAllService.getRecallManagerService().findRecallDetailList(recall.getId());
			this.baseAllService.getInStockManagerService().recallMinusInStock(recallDetailList);
			this.baseAllService.getRecallManagerService().updateRecallStatus(SystemConfig.RECALL_STATUS_APPROVAL, recall.getId());
			this.baseAllService.getRecallManagerService().updateAuditUser(auditUser, recall.getId());
			map.put("success", true);
		}else{
			map.put("message", "error");
			}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 查看出库单详细数据
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月13日,下午10:31:11
	 */
	@Action(value = "recall_data_view", results = {@Result(name = SUCCESS, location = "recall_data_view.jsp")})
	public String dataView(){
		return SUCCESS;
	}
	
	/**
	 * @desc 待审核出库单页面初始化
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月19日,下午3:19:50
	 */
	@Action(value = "recall_audit_init", results = {@Result(name = SUCCESS, location = "recall_audit_init.jsp")})
	public String auditInit(){
		return SUCCESS;
	}
	
	/**
	 * @desc 分页查询待审核出库单
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月19日,下午3:21:00
	 */
	@Action(value = "recall_audit_view")
	public String auditView(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = ServletActionContext.getContext().getParameters();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		recall.setHospitalId(admin.getEnterpriseId());
		pageBean = this.baseAllService.getRecallManagerService().findRecallAuditByPage(map, recall);
		map.clear();
		map.put("total", pageBean.getTotalRow());
		map.put("data", pageBean.getResult());
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 审核出库单
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月19日,下午3:39:18
	 */
	@Action(value = "recall_audit", results = {@Result(name = SUCCESS, location = "recall_audit.jsp")})
	public String audit(){
		return SUCCESS;
	}
	
	/**
	 * @desc 不同意出库更新出库单状态
	 * @return
	 * @author kangyj
	 * @datetime 2014年8月19日,下午4:17:58
	 */
	@Action(value = "recall_audit_reject")
	public String reject(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin auditUser = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(StringUtils.isNotBlank(recall.getId())){
			this.baseAllService.getRecallManagerService().updateAuditUser(auditUser, recall.getId());
			this.baseAllService.getRecallManagerService().updateRecallStatus(SystemConfig.RECALL_STATUS_REJECT, recall.getId());
			map.put("success", true);
		}else{
			map.put("message", "error");
			}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 导出出库清单
	 * @return
	 * @author hufq
	 * @datetime 2014年9月30日,上午11:07:45
	 */
	@Action(value="recall_export")
	public String export(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		try {
			response.addHeader("Content-Disposition", "attachment;filename=" + FileNameEncoderUtil.encode(request,"药品出库表.xls"));
			response.setContentType("application/vnd.ms-excel");
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			Workbook workbook = this.baseAllService.getRecallManagerService().exportRecallData(recall.getId());
		
			workbook.write(toClient);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @desc 打开导入页面
	 * @return
	 * @author hufq
	 * @datetime 2014年10月8日,下午6:18:00
	 */
	@Action(value="recall_import_add",results={@Result(name="SUCCESS",location="recall_import_add.jsp")})
	public String importAdd(){
		return SUCCESS;
	}
	
	/**
	 * @desc 导入Excel
	 * @return
	 * @author hufq
	 * @datetime 2014年10月9日,下午10:49:59
	 */
	@Action(value="recall_import_save")
	public String importSave(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		map = new HashMap<String, Object>();
		File file = this.getImportFile(request);
		try {
			MedicalAdmin writeUser = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			String errorInfo = this.baseAllService.getRecallManagerService().importRecallData(file, writeUser);
			if(SystemConfig.IMPORT_RECALL_SERIALNUM.equals(errorInfo)){
				map.put("success", false);
				map.put("errorInfo", "编号已存在");
			}else{
				map.put("success", true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 导入后删除文件
	 * @return null
	 * @author hufq
	 * @datetime 2014年10月9日,下午10:55:01
	 */
	@Action(value = "recall_import_del")
	public String delExcel(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		recall.setFilePath(recall.getFilePath().substring(recall.getFilePath().indexOf("/upload")));
		String absolutePath = ServletActionContext.getServletContext().getRealPath(recall.getFilePath());
		this.baseAllService.getMedicineService().delExcel(absolutePath);
		map.put("success", true);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 提交出库单审核
	 * @return null
	 * @author liy
	 * @datetime 2014年12月24日,上午10:34:32
	 */
	@Action(value = "recall_to_audit")
	public String toAudit(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		boolean flag = this.baseAllService.getRecallManagerService().toAudit(this.recall.getId());
		if(flag){
			map.put("success", true);
		}else{
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 下载药品出库导入模版
	 * @return null
	 * @author zhaoey
	 * @datetime 2015年4月7日,下午1:21:03
	 */
	@Action(value = "recall_download")
	public String recallDownload() {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		try {
			MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			response.addHeader("Content-Disposition", "attachment;filename=" + FileNameEncoderUtil.encode(request,"导入药品出库模板.xls"));
			response.setContentType("application/vnd.ms-excel");
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			Workbook workbook = this.baseAllService.getRecallManagerService().downloadRecallTemp(user);
			workbook.write(toClient);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public MedicalRecall getModel() {
		return recall;
	}
	
	
}